﻿using LL2024.Models.CommonLibraries.Interface;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace LL2024.Models.CommonLibraries.Services
{

    //长期维护此库原始起于物流项目
    public class AESHelperService : IAESHelper
    {
        private readonly string Key = "w@Z4P6F8S0p2h4Py"; // 必须是 16, 24 或 32 字符以对应 128, 192 或 256 比特密钥
        private readonly string IV = "aZPF5cNPYsJnHllA"; // 必须是 16 字符

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public string ToEncrypt(string plainText)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(Key);
                aesAlg.IV = Encoding.UTF8.GetBytes(IV);

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        return Convert.ToBase64String(msEncrypt.ToArray());
                    }
                }
            }
        }


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cipherText"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>

        public string ToDecrypt(string cipherText, string password)
        {
            if (password != "zpypyandhl") return "解密密钥错误";
            try
            {
                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.Key = Encoding.UTF8.GetBytes(Key);
                    aesAlg.IV = Encoding.UTF8.GetBytes(IV);

                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            {
                                return srDecrypt.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch
            {
                return "";
                // throw new Exception("解密失败", ex);
            }
        }
    }

}
